$(function(){

    let client = new WSSHClient();

    let option = {};

    $('.navbar .navbar-nav').on('click','.new_session',newSession);
    $('.modal .modal-footer').on('click','.btn-connect',connect);

    /**
     * 创建一个新会话
     */
    function newSession () {
        $('#sshConnectModal').modal('show');
    }

    function connect() {

        let host = $('#host').val(),
            port = $('#port').val(),
            name = $('#userName').val(),
            pwd  = $('#password').val();
        if (isEmpty(host)) {
            return;
        }
        if (isEmpty(name)) {
            return;
        }
        if (isEmpty(pwd)) {
            return;
        }

        let options = {
            "operate":"connect",
            "host":host,
            "port":port,
            "username":name,
            "password":pwd,
            "command":""
        }
        $.extend(option,options);
        clearInput();
        // 连接
        $('#sshConnectModal').modal('hide');
    }

    function isEmpty (str) {
        return (str === '' || str.length === 0);
    }

    $('#sshConnectModal').on('hidden.bs.modal',openTerminal);

    function openTerminal () {
        let term = new Terminal({
            cols: 97,
            rows: 37,
            cursorBlink: true, // 光标闪烁
            cursorStyle: "block", // 光标样式  null | 'block' | 'underline' | 'bar'
            scrollback: 10000, //回滚
            tabStopWidth: 8, //制表宽度
            screenKeys: true
        });
        term.on('data', function (data) {
            //键盘输入时的回调函数
            client.sendClientData(data);
        });
        term.open(document.getElementById('terminal'));
        //在页面上显示连接中...
        term.write('Connecting...\r\n');

        //执行连接操作
        client.connect({
            onError: function (error) {
                //连接失败回调
                term.write('Error: ' + error + '\r\n');
            },
            onConnect: function () {
                //连接成功回调
                client.sendInitData(option);
            },
            onClose: function () {
                //连接关闭回调
                term.write("\rconnection closed");
            },
            onData: function (data) {
                //收到数据时回调
                if (data.indexOf('\r\nlogout')>-1){
                    window.localStorage.clear();
                }
                term.write(data);
            }
        });
    }

    function clearInput(){
        $('#host').val('');
        $('#port').val('');
        $('#userName').val('');
        $('#password').val('');
    }


})